/**
 * 
 */
var map;
var chart;
var infoWindow;
var elevationMarker;
var minElevationMarker;
var maxElevationMarker;
var elevationService = new google.maps.ElevationService();
var elevations;
var elevations2;
datos = [];
var elevation;
var poliArray = [];
var polyline;
var cont=-1;
var info="";


google.load("visualization", "1", {packages: ["corechart"]});


function createMap(initialLocation,cursor){

    var myOptions = {
    	zoom: 8,
    	center: initialLocation,
    	mapTypeId: google.maps.MapTypeId.ROADMAP,
    	streetViewControl: false,
    	draggableCursor: cursor,
    	mapTypeControlOptions: {
    		mapTypeIds: [google.maps.MapTypeId.ROADMAP,
    		             google.maps.MapTypeId.HYBRID,
    		             google.maps.MapTypeId.TERRAIN,
    		             'routes'],
    		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    	}
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

    infoWindow = new google.maps.InfoWindow();
}

function createMapOff(initialLocation,cursor){

     var myOptions = {
    	zoom: 8,
    	center: initialLocation,
    	mapTypeId: google.maps.MapTypeId.HYBRID,
    	streetViewControl: false,
    	draggableCursor: cursor,
    	mapTypeControlOptions: {
    		mapTypeIds: [
    		             google.maps.MapTypeId.ROADMAP,
    		             google.maps.MapTypeId.HYBRID,
    		             
    		             'routes'],
    		style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
    	}
    };
    map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);

    infoWindow = new google.maps.InfoWindow();
}

function drawPolyline(routes,borrar){
      
      //alert (cont);
      
      if(borrar==true){
      	
         if (poliArray) {
         	
         	//alert(poliArray.length-1);
            poliArray[cont].setMap(null); 
            cont=cont-1;
           
            //poliArray[poliArray.length-1]=null;

       }
      }
      
      else{
      	
      	polyline = new google.maps.Polyline({
        path: routes
        , map: map
        , strokeColor: '#ff0000'
        , strokeWeight: 3
        , strokeOpacity: 1
        , clickable: false
      });
      
       cont=cont+1;
       poliArray.push(polyline);
      	
      }
      
      //alert (cont);
      
   /*   
     
       *Distancia entre 2 coordenadas
       *  
       * var R = 6371; // km
		var dLat = (lat2-lat1).toRad();
		var dLon = (lon2-lon1).toRad();
		var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
        Math.sin(dLon/2) * Math.sin(dLon/2);
		var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		var d = R * c;
       * 
       */


}



function setBlueStyle(){
	var stylez=[{ 
		featureType: "road", 
		elementType: "all", 
		stylers: [ { saturation: 0 }, { hue: "#0077ff" } ] 
	}]; 
	var styledMapOptions = { name: "Routes"};
	var routesMapType = new google.maps.StyledMapType(stylez, styledMapOptions);
	map.mapTypes.set('routes', routesMapType);
	map.setMapTypeId('routes');
}

function locateUser() {
	if (navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position) {
			initialLocation = new google.maps.LatLng(position.coords.latitude,
					position.coords.longitude);
			//var info=position.coords.latitude+","+position.coords.longitude;
			//alert(info);
			map.setCenter(initialLocation);
			
		}, function() {
			handleNoGeolocation(browserSupportFlag);
		});
	} else {
		initialLocation = new google.maps.LatLng(-34.397, 150.644);
	}
	return initialLocation;
}

function locatePosition() {
	if (navigator.geolocation) {
		browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(function(position){
			//alert("InformaciónPosicion");
			info=position.coords.latitude+","+position.coords.longitude;
			//alert(info);
	}, function() {
			handleNoGeolocation(browserSupportFlag);
		});
	return info;
}}

function drawElevation(path){
	$("#elevacion").slideUp("slow");
	// Create a PathElevationRequest object using this array.
    // Ask for 256 samples along that path.
	
	//Al parecer la ElevationRequest no funciona cuando el path es muyy largo 
	//(mas de unos 400 puntos).
	//Aqui lo reduzco lo minimo posible buscando el mayor factor si el path es 
	//mayor de 512, no se si es el mejor metodo.
	//Podr�a hacerse varias requests para el mismo path quiz�s.
	var reducedPath=new Array();
	reducedLength=path.length;
	
	if(reducedLength>512){
		var factor=1;
		while(reducedLength>512){
			factor++;
			reducedLength=reducedLength/factor;
		}
		var j=0;
		for(var i=0;i<path.length;i=i+factor){
			reducedPath[j]=path[i];
			j=j+1;
		}
	}
	else{
		reducedPath=path;
	}
    var pathRequest = {
      'path': reducedPath,
      'samples': 256
    };
    // Initiate the path request.
    elevationService.getElevationAlongPath(pathRequest, plotElevation);
    
   
}

//Takes an array of ElevationResult objects, draws the path on the map
//and plots the elevation profile on a Visualization API AreaChart.
function plotElevation(results, status) {
	
	if (status == google.maps.ElevationStatus.OK) {
	  elevations = results;
	  
	  // Create a new chart in the elevation_chart DIV.
	  chart = new google.visualization.AreaChart(document.getElementById('elevation_chart'));
	  
	  // Extract the data from which to populate the chart.
	  // Because the samples are equidistant, the 'Sample'
	  // column here does double duty as distance along the
	  // X axis.
	  var data = new google.visualization.DataTable();
	  data.addColumn('string', 'Sample');
	  data.addColumn('number', R_COMMON_ELEVATION);
	  for (var i = 0; i < results.length; i++) {
		  data.addRow(['',elevations[i].elevation]);
	  }
	
	  // Draw the chart using the data within its DIV.
	  document.getElementById('elevation_chart').style.display = 'block';
	  chart.draw(data, {
		width: 810,
		height: 150,
	    legend: 'none',
	    titleY: R_COMMON_ELEVATION,
	    pointSize: 0,
	    backgroundColor: {fill: '#FFFFFF'},
	    colors:['#9db82f','#004411']
	  });
	  google.visualization.events.addListener(chart, 'onmouseover', onMouseOverHandler);
	  
	  //Draw higher and lower markers
	  drawMaxMinElevations();
	  $("#elevacion").slideDown("slow");
	}
	else if(status == google.maps.ElevationStatus.INVALID_REQUEST){
		alert("Invalid request");
	}
	else if(status == google.maps.ElevationStatus.OVER_QUERY_LIMIT){
		alert("Over query limit");
	}
	else if(status == google.maps.ElevationStatus.REQUEST_DENIED){
		alert("Request denied");
	}
	else if(status == google.maps.ElevationStatus.UNKNOWN_ERROR){
		alert("Unknown error");
	}
}

function createMaxMinElevationMarkers(maxElevation,minElevation){
	//Maximum elevation marker
	var imageMaxElev="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.5|0|FF0000|11|_|H";
	maxElevationMarker = new google.maps.Marker({
		position: maxElevation.location, 
		map: map,
		icon: imageMaxElev
	});
	
	//Minimum elevation marker
	var imageMinElev="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.5|0|2E9AFE|11|_|L";
	minElevationMarker = new google.maps.Marker({
		position: minElevation.location, 
		map: map,
		icon: imageMinElev
	});	
}

function drawMaxMinElevations(){
	
	var maxElevation=new Object({
		elevation: elevations[0].elevation,
		location: elevations[0].location
	});
	var minElevation=new Object({
		elevation: elevations[0].elevation,
		location: elevations[0].location
	});

	for(var i = 0; i < elevations.length; i++){
		if(elevations[i].elevation>maxElevation.elevation){
			maxElevation.elevation=elevations[i].elevation;
			maxElevation.location=elevations[i].location;
		}
		if(elevations[i].elevation<minElevation.elevation){
			minElevation.elevation=elevations[i].elevation;
			minElevation.location=elevations[i].location;
		}
	}
	
	if(maxElevationMarker!=null && minElevationMarker!=null){
		maxElevationMarker.setPosition(maxElevation.location);
		minElevationMarker.setPosition(minElevation.location);
		
		maxElevationMarker.setVisible(true);
		minElevationMarker.setVisible(true);	
	}
	else{
		createMaxMinElevationMarkers(maxElevation,minElevation);
	}
	addInfoWindowListeners(maxElevation,minElevation);
}

function onMouseOverHandler(event){
	if(elevationMarker!=null){
		elevationMarker.setVisible(true);
		elevationMarker.setPosition(elevations[event['row']].location);
	}
	else{
		var imageElev="http://chart.apis.google.com/chart?chst=d_map_spin&chld=0.35|0|FFFFFF|11|_|";
		elevationMarker = new google.maps.Marker({
			position: elevations[event['row']].location, 
			map: map,
			icon: imageElev
		});	
	}
}
2
function addInfoWindowListeners(maxElevation,minElevation){
	//Maximum elevation marker infoWindow
	google.maps.event.addListener(maxElevationMarker, 'click', function() {
		infoWindow.setContent(R_COMMON_MAXELEV+": "+Math.round(maxElevation.elevation)+" m");
		infoWindow.open(map,maxElevationMarker);
	});
	//Minimum elevation marker infoWindow
	google.maps.event.addListener(minElevationMarker, 'click', function() {
		infoWindow.setContent(R_COMMON_MINELEV+": "+Math.round(minElevation.elevation)+" m");
		infoWindow.open(map,minElevationMarker);
	});
}

function getTimeForDistance(distance){
	var milliseconds = ((distance / 5.)-1)*60*60*1000;
	
	var seconds = Math.floor(milliseconds / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	
	minutes=minutes-hours*60;
	hours=hours-days*24;
	
	document.getElementById("distanceInfo").innerHTML="<b>"+R_COMMON_DISTANCE+": </b>"+ distance + " km";

	document.getElementById("time").innerHTML="<b>"+R_COMMON_TIME+": </b>";
	if(days!=0){
		if(days==1)
			document.getElementById("time").innerHTML= days+" "+R_COMMON_DAY;
		else
			document.getElementById("time").innerHTML= days+" "+R_COMMON_DAYS;
	}
	if(hours!=0){
		if(hours==1)
			document.getElementById("time").innerHTML+=" "+ hours + " "+R_COMMON_HOUR+" "+R_COMMON_AND;
		else
			document.getElementById("time").innerHTML+=" "+ hours + " "+R_COMMON_HOURS+" "+R_COMMON_AND;
	}
	document.getElementById("time").innerHTML+=" "+minutes+" "+R_COMMON_MINUTES;
	$("#distanceTime").slideDown("slow");
	$("#saveRoute").slideDown("slow");
}

function pointToKML(latLng){
	var location=""+latLng.lng()+","+latLng.lat();
	return location;
}

function lineToKML(latLngArray){
	var kmlDirection="";
	for (var i = 0; i < latLngArray.length; i++) {
		kmlDirection+=""+latLngArray[i].lng()+","+latLngArray[i].lat()+" ";
	}
	return kmlDirection;
}

function getElevation(path){
	
	var reducedPath=new Array();
	reducedLength=path.length;
	
	
	if(reducedLength>512){
		var factor=1;
		while(reducedLength>512){
			factor++;
			reducedLength=reducedLength/factor;
		}
		
		var j=0;
		for(var i=0;i<path.length;i=i+factor){
			reducedPath[j]=path[i];
			j=j+1;
		}
		
	}
	else{
		reducedPath=path;
	}
	
	    
    
    var pathRequest = {
      'path': reducedPath,
      'samples': 256
    };
    
    // Create an ElevationService
  	elevator = new google.maps.ElevationService();
  	 //alert(path);
    //return (elevator.getElevationAlongPath(pathRequest, respuesta));
    var positionalRequest = {'locations': path};
    return(elevator.getElevationForLocations(positionalRequest, respuesta));
     
}



function respuesta (results, status) {

	if (status == google.maps.ElevationStatus.OK) {
		
		elevations2 = results;
		
		for (var i = 0; i < results.length; i++) {
        	datos.push(elevations2[i].elevation);
	  	}

	} else{
		//alert("meeeeeeeeccc");
	}
	return datos;
  
}